from django.core.cache import caches
from functools import wraps
import time

class RedisManager:
    """Redis主从管理器"""
    
    def __init__(self):
        self.master_cache = caches['default']
        self.slave_cache = caches['slave']
    
    def write_to_master(self, key, value, timeout=None):
        """写入主库"""
        return self.master_cache.set(key, value, timeout)
    
    def read_from_slave(self, key, default=None):
        """从从库读取，如果失败则从主库读取"""
        try:
            value = self.slave_cache.get(key, default)
            if value is None:
                value = self.master_cache.get(key, default)
            return value
        except:
            return self.master_cache.get(key, default)
    
    def delete_key(self, key):
        """删除键（从主库删除）"""
        return self.master_cache.delete(key)
    
    def incr(self, key):
        """递增（在主库上操作）"""
        return self.master_cache.incr(key)
    
    def use_master_for_reads(self, timeout=5):
        """装饰器：在指定时间内强制使用主库进行读取"""
        def decorator(func):
            @wraps(func)
            def wrapper(*args, **kwargs):
                try:
                    # 临时将主库用于读取
                    result = func(*args, **kwargs)
                    return result
                finally:
                    pass
            return wrapper
        return decorator
